package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.common.exception.BlogException;
import com.blog.common.utils.ConversionUtils;
import com.blog.mapper.UserInfoMapper;
import com.blog.pojo.dataobject.BlogInfo;
import com.blog.pojo.dataobject.UserInfo;
import com.blog.pojo.request.UserLoginRequest;
import com.blog.pojo.response.UserInfoResponse;
import com.blog.pojo.response.UserLoginResponse;
import com.blog.service.BlogService;
import com.blog.service.UserService;
import com.blog.common.utils.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    // 注入UserInfoMapper
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
   private BlogService blogService;

    // 实现checkPassword方法
    @Override
    public UserLoginResponse checkPassword(UserLoginRequest userLoginRequest) {
        // 创建QueryWrapper对象
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        // 使用lambda表达式设置查询条件
queryWrapper.lambda().eq(UserInfo::getUserName,userLoginRequest.getUsername())
        .eq(UserInfo::getDeleteFlag,0);
UserInfo userInfo=userInfoMapper.selectOne(queryWrapper);
if (userInfo == null) {
    throw new BlogException("用户不存在");
}
if(!userInfo.getPassword().equals(userLoginRequest.getPassword())){
    throw new BlogException("密码错误");
}
        Map<String,Object>map=new HashMap<>();
map.put("id",userInfo.getId());
map.put("username",userInfo.getUserName());
String token= JwtUtils.genToken(map);
UserLoginResponse userLoginResponse=new UserLoginResponse(token,userInfo.getId());
return userLoginResponse;
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
queryWrapper.lambda().eq(UserInfo::getId,userId).eq(UserInfo::getDeleteFlag,0);

UserInfo userInfo=userInfoMapper.selectOne(queryWrapper);
        return ConversionUtils.personToUserInfoResponse(userInfo);
    }

    @Override
    public UserInfoResponse getAuthoInfo(Integer blogId) {
       BlogInfo blogInfo=blogService.getBlogInfo(blogId);
if (blogInfo==null||blogInfo.getUserId()<=0){
    throw new BlogException("博客不存在");
}
        return getAuthoInfo(blogInfo.getUserId());
    }
}
